package com.dwjm.shop.Wwj.client;

import com.dwjm.shop.Wwj.Goods.Goods;
import com.dwjm.shop.Wwj.utils.ConnectionDatabaseForMySQLUseJdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class ConsumerDaoImpl implements ConsumerDao{
    Connection connection=null;
    PreparedStatement pstmt=null;
    ResultSet rset=null;
    public ConsumerDaoImpl(){
        connection= ConnectionDatabaseForMySQLUseJdbc.getConnection();
    }
//  获取所有的可销售商品的信息
    @Override
    public List<Goods> getAllGoods() {
        List<Goods> goodsList=new ArrayList<>();
        try {
            String sql="SELECT TOP 13 id, title, price, descr, img,  state, mid FROM t_goods WHERE state = 0 ORDER BY id";
            pstmt=connection.prepareStatement(sql);
            rset=pstmt.executeQuery();
            while(rset.next()){
                goodsList.add(new Goods(
                        rset.getInt("id"),
                        rset.getString("title"),
                        rset.getBigDecimal("price"),
                        rset.getString("descr"),
                        rset.getString("img"),
                        rset.getInt("state"),
                        rset.getInt("mid")));
            }
            goodsList.forEach(x-> System.out.println(x));
            return goodsList;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
//  消费者的注册
    @Override
    public int addConsumer(String account, String password) {
        try {
            pstmt=connection.prepareStatement("insert into t_consumer (account,password) values (?,?)");
            pstmt.setString(1,account);
            pstmt.setString(2,password);
            int i=pstmt.executeUpdate();
            return i;
        }catch (Exception e){
            e.printStackTrace();
            return  0;
        }
    }
//  消费者的登录
    @Override
    public Consumer login(String account, String password) {
        try {
            pstmt=connection.prepareStatement("select account,password from t_consumer where account=? and password=?");
            pstmt.setString(1,account);
            pstmt.setString(2,password);

            System.out.println(account + "" + password);

            rset=pstmt.executeQuery();
            Consumer consumer=new Consumer();
//            System.out.println(rset.next());
            if (rset.next()) {
                consumer.setAccount(rset.getString("account"));
                consumer.setPassword(rset.getString("password"));
                return consumer;
            }
            System.out.println(consumer);
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
